﻿// asio阻塞读写.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<boost/asio.hpp>


const int MAX_LENGTH = 1024;

int main()
{
    try {
        //创建上下问服务
        boost::asio::io_context ioc;
        //
        boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 8080);
        boost::asio::ip::tcp::socket sock(ioc);
        boost::system::error_code error = boost::asio::error::host_not_found;
        
        //客户端绑定想要发送数据的端点
        sock.connect(ep,error);
        if (error) {
            std::cout << "connect failed, code is " << error.value() << " error msg is " << error.message() << std::endl;
            return 0;
        }

        //客户端发送数据
        std::cout << "Enter message: ";
        char request[MAX_LENGTH];
        std::cin.getline(request,MAX_LENGTH);
        size_t request_length = strlen(request);
        boost::asio::write(sock, boost::asio::buffer(request, request_length));

        //客户端接收数据
        char reply[MAX_LENGTH];
        size_t reply_length = boost::asio::read(sock, boost::asio::buffer(reply,request_length));
        std::cout << "Reply is: ";
        std::cout.write(reply,reply_length);
        std::cout << std::endl;

    }
    catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
    return 0;
}

